package com.lhy.ltss.service;

import com.lhy.ltss.common.UserRoleConst;
import com.lhy.ltss.entity.Page;
import com.lhy.ltss.exception.LoginException;
import com.lhy.ltss.dao.UserDao;
import com.lhy.ltss.entity.User;
import com.lhy.ltss.session.UserManage;
import com.lhy.ltss.util.Password;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @description:
 * @author: 李汇远
 */
@Service
@Transactional
public class UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    UserManage userManage;

    final String DEFAULT_ADMIN="admin";

    /**
     * 登录操作
     * @param username
     * @param password
     * @throws LoginException
     */
    public User login(String username, String password) throws LoginException {
        User user = userDao.get(username);
        if (user == null){
            if (DEFAULT_ADMIN.equals(username)){
                // 如果没有默认的管理员账号，就注册一个
                user = new User();
                user.setUsername(DEFAULT_ADMIN);
                user.setName(DEFAULT_ADMIN);
                user.setRole(UserRoleConst.ADMIN);
                addUser(user);
            }else {
                throw new LoginException("用户名不存在");
            }
        }
        String dbPwd = user.getPassword();
        if (!Password.check(dbPwd, password)){
            throw new LoginException("用户密码错误");
        }
        userManage.saveUser(user);
        // 清除密码
        user.setPassword(null);
        return user;
    }

    public void logout(){
        userManage.clearUser();
    }

    public Integer updateUser(String name, String tel){
        String username = userManage.getUsername();
        return userDao.update(name, tel, username);
    }

    public Integer updateUserPwd(String oldPwd, String newPwd) {
        String username = userManage.getUsername();
        newPwd = Password.getEncryption(newPwd);
        oldPwd = Password.getEncryption(oldPwd);
        int res = userDao.updateUserPwd(newPwd, oldPwd, username);
        return res;
    }

    // 添加用户
    public Integer addUser(User user){
        // 对密码加密, 默认密码为用户名
        user.setPassword(Password.getEncryption(user.getUsername()));
        return userDao.addUser(user);
    }

    // 重置用户密码，默认密码为用户名
    public Integer resetPwd(String username){
        return userDao.updateUserPwd2(Password.getEncryption(username), username);
    }

    // 获取用户列表，分页，条件查询（右边模糊匹配）
    public Page<User> getUsers(String username, Integer page){
        username += "%";
        List<User> users = userDao.getUsers(username, (page - 1) * 10);
        int totalPage = userDao.countUsers(username);
        totalPage = totalPage == 0 ? 1 : totalPage / 10 + 1;
        return new Page<>(page, totalPage, users);
    }
}
